package com.stupidzhe.jdklearning.concurrency.sync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: StupidZhe
 * @Date: Created in 2017/11/25
 * @Description: 使用synchronized关键词来锁定对象
 */
public class SyncTest implements Runnable {

    private static int a;

    public void print() {
        System.out.println(++a);
    }

    public static void main(String[] args) {
        SyncTest syncTest = new SyncTest();
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executor.execute(new Thread(syncTest));
        }
        executor.shutdown();
    }

    @Override
    public void run() {
        while (a < 100) {
            try {
                Thread.sleep(500);
                synchronized (this) {
                    print();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
